namespace pengpeng{
	export class PixiBox2DWorld extends PPWorld
	{
		public worldView:PIXI.Container;
		public phyWorld:Box2D.Dynamics.b2World;
		public velocityIterations:number;//"velocityIterations":6,
        public positionIterations:number;//"positionIterations":2,

		public m_physScale:number = 10;
		public m_sprite:PixiDebugDraw;
		private bodyViewMap:Map<string,PIXI.Sprite>;

		public constructor(world:Box2D.Dynamics.b2World, debugDraw:boolean = false) 
		{
			super();
			this.worldView = new PIXI.Container();
			this.phyWorld = world;
			this.bodyViewMap = new Map<string,PIXI.Sprite>();

			if(debugDraw)
			{
				this.m_sprite = new PixiDebugDraw();
				let dbgDraw:Box2D.Dynamics.b2DebugDraw = new Box2D.Dynamics.b2DebugDraw();
				dbgDraw.SetSprite(this.m_sprite);
				dbgDraw.SetDrawScale(this.m_physScale);
				dbgDraw.SetFillAlpha(0.3);
				dbgDraw.SetLineThickness(2.0);
				dbgDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit | 
								Box2D.Dynamics.b2DebugDraw.e_jointBit);
				this.phyWorld.SetDebugDraw(dbgDraw);

				this.worldView.addChild(this.m_sprite);
			}
			

		}

		public bindBodyView(bodyId:string, bodyView:PIXI.Sprite):void
		{
			this.bodyViewMap[bodyId] = bodyView;
			this.worldView.addChild(bodyView);
		}

		public run():void
		{
			PIXI.ticker.shared.add(this.tick, this);
		}

		/**
		 * 停止
		 */
		public stop():void
		{
			PIXI.ticker.shared.remove(this.tick,this);
		}

		/**
		 * 重新开始
		 */
		public restart():void
		{

		}

		/**
		 * 暂停模拟
		 */
		public pause():void
		{

		}
		/**
		 * 销毁，释放内存
		 */
		public destroy():void
		{

		}

		private tick(deltaTime:number):void
		{
			if(this.phyWorld)
			{
				this.phyWorld.Step(PIXI.ticker.shared.elapsedMS / 1000,this.velocityIterations, this.positionIterations);
				this.phyWorld.ClearForces();
				this.phyWorld.DrawDebugData();
				
				let body:Box2D.Dynamics.b2Body = this.phyWorld.GetBodyList();
				while(body != null)
				{
					let bodyId:string = body.GetUserData();
					let bodyView:PIXI.Sprite = this.bodyViewMap[bodyId];
					if(bodyView)
					{
						let pos = body.GetPosition();
						let ang = body.GetAngle();
						bodyView.x = pos.x;
						bodyView.y = pos.y;
						bodyView.rotation = ang;
					}
					body = body.GetNext();
				}
			}
			
		}
	}
}
